import Feature from '../feature/feature';
/**
 * 针对新要素，生成的唯一标识
 * @returns
 */
export function generateId(type: string = 'N'): string {
    const ngMaxId = localStorage.getItem('NG_MAX_ID');

    let id: number = 0;

    if (ngMaxId !== null) {
        id = Number(ngMaxId);
    }

    id--;
    localStorage.setItem('NG_MAX_ID', '' + id);

    return 'client' + '_' + type + '_' + id;
}

export function getAnotation(prev: string, feature?: Feature) {
    return feature ? prev + ':' + feature.id : prev;
}

export function debounced(func: Function, delay: number, immediate: boolean = false): Function {
    let timer: NodeJS.Timeout | undefined;
    const _this: any = this;
    return (...args: any) => {
        if (immediate) {
            func.apply(_this, args); // 确保引用函数的指向正确，而且函数的参数也不变
            immediate = false;
            return;
        }
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(_this, args);
        }, delay);
    };
}

export function deepClone(obj: any) {
    // 判断如果不是引用类型，直接返回数据即可
    if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || typeof obj === 'undefined') {
        return obj;
    } else {
        const objClone: any = Array.isArray(obj) ? [] : {};
        if (obj && typeof obj === 'object') {
            for (const key in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, key)) {
                    if (obj[key] && typeof obj[key] === 'object') {
                        objClone[key] = deepClone(obj[key]);
                    } else {
                        objClone[key] = obj[key];
                    }
                }
            }
        }
        return objClone;
    }
}
